package middleware

import (
	"strings"
	"tdy-backend/app/core"
	"tdy-backend/global"
	"tdy-backend/utils"

	"github.com/gin-gonic/gin"
)

func JwtAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		path := c.Request.URL.Path
		noCheckAuth := global.TYD_CONFIG.GetStringSlice("auth.noCheck")
		for _, s := range noCheckAuth {
			if strings.HasPrefix(path, s) {
				c.Next()
				return
			}
		}

		token := c.Request.Header.Get("token")
		if strings.HasPrefix(path, "/ws") {
			token = c.Query("token")
		}
		if token == "" {
			core.AuthError(c, "非法登录")
			c.Abort()
			return
		}
		_, err := utils.ParseToken(token)
		if err != nil {
			core.AuthError(c, "未登录")
			c.Abort()
			return
		}
		c.Next()

	}
}
